<template>
    <n-data-table :columns="curColumns" :data="curData" :pagination="false" :loading="loading"
        :row-key="(row) => row[curConf.idKey]" v-bind="$attrs" />
</template>

<script lang="ts" setup>
import { computed, PropType, ref, watch,h } from "vue";
import { IBaseTableConfig, ColumnsConfig } from "./type";
import { beforeColumns } from "./util";
import { controlsMap,getEditControl,getBaseConf } from "./editControl";
const props = defineProps({
    data: {
        type: Array,
        default: () => [],
    },
    columns: {
        type: Array as PropType<ColumnsConfig[]>,
        default: () => [],
    },
    config: {
        type: Object as PropType<IBaseTableConfig>,
        default: () => ({}),
    },
});
const defConf = {
    page: 1,
    size: 10,
    pageKey: "page",
    sizeKey: "size",
    pageSizes: [10, 20, 30, 40, 50, 100],
    fixQuery: {},
    idKey: "id",
};
const loading = ref(false);

const emits = defineEmits(["update:data"]);

const curConf = computed(() => {
    return Object.assign({}, defConf, props.config);
});

const getSourceData = () => {
    return JSON.parse(JSON.stringify(props.data || []));
};
const curData = ref(getSourceData());

// 处理cols
const curColumns = computed(() => {
    return props.columns.map((col: ColumnsConfig) => {
        col.minWidth = "100px";
        let curColConf = controlsMap[col.editType]
        if (col.editType && curColConf && curColConf.dom) {
            col.render = (row: any) => {
            let tpmConf = curColConf.conf(col)
            return col.changeEdit ? getEditControl(row, col, curColConf.dom, tpmConf) : h(curColConf.dom, {
                ...getBaseConf(row, col),
                ...tpmConf
            })
        };
        }
        beforeColumns(col);
        return col;
    });
});

const initData = () => {
    curData.value = getSourceData();
};

const onSearch = (q, isReset = true) => {
    if (isReset) {
        initData();
    } else {
        curData.value = curData.value.filter((item) => {
            return curConf.value.searchMap
                ? curConf.value.searchMap(q, item)
                : Object.keys(q).some((key) => {
                    return String(item[key]).includes(q[key]);
                });
        });
    }
};
const getUpdateData = () => {
    return curData.value;
};
watch(() => props.data, () => {
    initData();
},{
    deep:true
});

initData();
defineExpose({
    onSearch,
    getUpdateData,
});
</script>